#include "Service.h"
#include <iostream> //for log 
#include <cassert>

#include "NetFrameImplFactory.h"
#include "Impl.h"

namespace frame {

Service::Service(ImplFactory::Ptr factory)
: factory(factory)
, impl(factory->createService())
{
}

Service::~Service(){
}

int Service::start(){
    std::cout <<"Service::start"<<std::endl;
    for(auto & p : runObjects){
        p.second->open();
    }
    assert(impl != nullptr);
    return impl->start();
}

int Service::run(){
    std::cout <<"Service::run"<<std::endl;
    assert(impl != nullptr);
    return impl->run();
}


void Service::stop(){
    std::cout <<"Service::stop"<<std::endl;
    assert(impl != nullptr);
    impl->stop();
    for(auto & p :runObjects){
        p.second->close();
    }
    runObjects.clear();
}

uint64_t Service::add(IRunnable::Ptr runnable){
    assert(runnable != nullptr);

    uint64_t id = numbers.next();
    runnable->setId(id);
    runObjects.insert(std::make_pair(id, runnable));
    return id;
}

IRunnable::Ptr Service::get(uint64_t id) {
    auto iter = runObjects.find(id);
    if(iter != runObjects.end()){
        return iter->second;
    }
    return nullptr;
}
void Service::remove(uint64_t id) {
    auto iter = runObjects.find(id);
    if( iter != runObjects.end()){
        runObjects.erase(iter);
    }
}

} //end of namespace frame
